package com.wdb007.venus.svc.biz.utils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.util.ObjectUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

public class OSSUtil {

	public static Map<String, String> genOSSPostSignature(String dir,String bucket,String endpoint) {
		Map<String, String> respMap = new LinkedHashMap<String, String>();
		if(ObjectUtils.isEmpty(endpoint)) {
			endpoint = "sm.wdb007.com";
		}
        String accessId = "LTAI3FIgF26XglMg";
        String accessKey = "blEXM575lLjKYHpbclm0t4fmdCxz8l";
//		if(ObjectUtils.isEmpty(bucket)) {
//			bucket = "wdb-html";
//		}
		if(ObjectUtils.isEmpty(dir)) {
			dir = "repairsImg/";
		}
//        String host = "https://" + bucket + "." + endpoint;
        String host = "https://sm.wdb007.com";
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try { 	
        	long expireTime = 30;
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            
        } catch (Exception e) {
        		e.printStackTrace();
        }
		return respMap;
	}
}
